package com.bahiaapk.services;

import java.util.List;
import org.json.JSONArray;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import blueprint.software.blueframe.exceptions.BlueFrameException;
import blueprint.software.blueframe.synchronize.HTTPConnect;
import com.bahiaapk.dao.TwitterMessageDAO;
import com.bahiaapk.dao.TwitterUserDAO;
import com.bahiaapk.dto.TwitterUser;
import com.bahiaapk.util.BahiaUtil;

public class SynchronizeTwitter implements Runnable {
	 
	 private Handler handler;
	 private Context context;
	 private HTTPConnect connect;
	 private TwitterMessageDAO twitterMessageDAO;
	 private TwitterUserDAO twitterUserDAO;
	 private final Thread thread = new Thread(this);

	 public void synchronize(Context context, Handler handler){
		 
		 this.handler = handler;
		 this.context= context;
		 twitterMessageDAO = new TwitterMessageDAO(context);
		 twitterUserDAO = new TwitterUserDAO(context);
		 thread.start();
	 }
	 
	
	@Override
	public void run() {
		Bundle data = new Bundle();
		
		List<TwitterUser> lTwitterUsers  = twitterUserDAO.findAll();
		if(BahiaUtil.haveNetworkConnection(context)){
			for (TwitterUser twitterUser : lTwitterUsers) {
				connect = new HTTPConnect("https://api.twitter.com/1/statuses/user_timeline.json?contributor_details=false&trim_user=false&include_rts=true&include_entities=true&count=20&screen_name="+twitterUser.getName());
				JSONArray array;
				try {
					array = connect.getArrayTwits("", null);
					if(array!=null && array.length()>0){
						twitterMessageDAO.insert(array, twitterUser.getName());
					}
					
				} catch (BlueFrameException e) {
					Log.e(BahiaUtil.TAG,e.getMessage());
				}catch (Exception e) {
					Log.e(BahiaUtil.TAG,e.getMessage());
				}
			}
		}
		
		data.putBoolean("status", true);
		
		Message msg = new Message();
		msg.setData(data);
						

		handler.sendMessage(msg);
		
	}
}